import 'package:fish_redux/fish_redux.dart';
import 'package:kunlun_gas/AppViews/EngineerOrderView/model/meter_info_model.dart';
import '../model/normal_config_model.dart';
import 'dart:io';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'dart:convert' as convert;

Effect<EngineerGasResultViewState> buildEffect() {
  return combineEffects(<Object, Effect<EngineerGasResultViewState>>{
    EngineerGasResultViewAction.onTapAddPic: _onTapAddPic,
    EngineerGasResultViewAction.onTapPic: _onTapPic,
    EngineerGasResultViewAction.onSubmit: _onSubmit,
    EngineerGasResultViewAction.onTapSign: _onTapSign,
    EngineerGasResultViewAction.onTapResultPic: _onTapResultPic,
    EngineerGasResultViewAction.onSave: _onSave,
    Lifecycle.initState: _initState,
    EngineerGasResultViewAction.onTapAddGasPic: _onTapAddGasPic,
    EngineerGasResultViewAction.onTapGasPic: _onTapGasPic,
    EngineerGasResultViewAction.onTapIdCard: _onTapIdCard,
  });
}

void _onAction(Action action, Context<EngineerGasResultViewState> ctx) {}

void _onTapIdCard(
    Action action, Context<EngineerGasResultViewState> ctx) async {
  var idCard;

  if (!ctx.state.isDetail) {
    AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(
        ctx.context,
        type: 2,
        info: ctx.state.model);
    if (action.payload == 'fan') {
      ctx.state.idCardBackImg = imgFile;
    } else {
      ctx.state.idCardFrontImg = imgFile;
    }
    ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
  } else {
    if (action.payload == 'fan') {
      idCard = ctx.state.idCardBackImg;
    } else {
      idCard = ctx.state.idCardFrontImg;
    }
    List<GalleryExampleItem> items = [
      GalleryExampleItem(
        id: '0',
        resource: idCard,
      )
    ];
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: 0,
      galleryItems: items,
    );
  }
}

void _initState(Action action, Context<EngineerGasResultViewState> ctx) async {
  if (ctx.state.isDetail) {
    ResultData res = await CommonNetWork.fixOrderDetail(ctx.state.model.itemID);
    if (res.success) {
      if (ctx.state.model.meterContent.isNotEmpty) {
        Map info = convert.jsonDecode(ctx.state.model.meterContent);
        ctx.state.meterInfoModel = MeterInfoModel();
        ctx.state.meterInfoModel.setJsonInfo(info);
      }
      ctx.dispatch(
          EngineerGasResultViewActionCreator.onGetData(res.data['data']));
    } else {
      await CommonUtils.showAlertView(ctx.context, res.desc);
      Navigator.pop(ctx.context);
    }
  }
  // else {
  //   if (ctx.state.meterInfoModel != null) {
  //     ctx.state.idCard = ctx.state.meterInfoModel.userIdNo;
  //   }
  // }
}

void _onTapAddPic(
    Action action, Context<EngineerGasResultViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 2, info: ctx.state.model);
  if (imgFile != null) {
    ctx.state.orderPhoto.add(imgFile);
    ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
  }
}

void _onTapPic(Action action, Context<EngineerGasResultViewState> ctx) async {
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: ctx.state.orderPhoto.indexOf(file),
      files: ctx.state.orderPhoto,
    );
  }

  var file = action.payload;
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
        await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.orderPhoto.remove(file);
      ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}

void _onSave(Action action, Context<EngineerGasResultViewState> ctx) async {
  CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
  List items = ctx.state.items.map((e) => e.toJson()).toList();
  for (var item in items) {
    List imgList = item['ImageList'];
    if (imgList != null && imgList.isNotEmpty) {
      List<String> uploads = await CommonNetWork.multiUploadImgs(imgList,
          userNo: ctx.state.model.itemID);
      if (uploads == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      item['ImageList'] = uploads;
    }
  }
  String json = convert.jsonEncode(items);
  List<String> orderPhoto = [];
  if (ctx.state.orderPhoto.isNotEmpty) {
    orderPhoto = await CommonNetWork.multiUploadImgs(ctx.state.orderPhoto,
        userNo: ctx.state.model.itemID);
    if (orderPhoto == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
  }
  String signPhoto = '';
  if (ctx.state.orderSignPhoto != null) {
    List<String> items = await CommonNetWork.multiUploadImgs(
        [ctx.state.orderSignPhoto],
        userNo: ctx.state.model.itemID);
    if (items == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    signPhoto = items.first;
  }

  Navigator.pop(ctx.context);
  CommonUtils.showWaitLoading(ctx.context, descText: '正在提交中');
  print(json);
  ResultData res = await CommonNetWork.fixOrderSubmit(
    orderPhoto: orderPhoto.join(','),
    jsonContent: json,
    signPhoto: signPhoto,
    isSolve: ctx.state.isSolve,
    itemID: ctx.state.model.itemID,
    bizMeterContent: '',
    isSave: true,
  );

  Navigator.pop(ctx.context);
  if (res.success) {
    bus.emit('refreshList');
    await CommonUtils.showAlertView(ctx.context, '提交成功');
    Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onSubmit(Action action, Context<EngineerGasResultViewState> ctx) async {
  bool isSave = action.payload;
  if (ctx.state.orderSignPhoto == null) {
    var res = await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
    if (res != null) {
      ctx.state.orderSignPhoto = res;
      ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
    }
  } else {
    if (ctx.state.isSolve == null && !isSave) {
      CommonUtils.showErrorInfo(ctx.context, '请选择状态');
      return;
    }
    if (ctx.state.idCard.length == 0) {
      CommonUtils.showErrorInfo(ctx.context, '请输入身份证号');
      return;
    }
    if (ctx.state.orderPhoto.length == 0 && ctx.state.model.itemType != '6') {
      CommonUtils.showErrorInfo(ctx.context, '请拍照留存');
      return;
    }
    String bizMeterContent = '';
    if (ctx.state.meterInfoModel != null) {
      CommonUtils.showWaitLoading(ctx.context, descText: '添加表具中');
      MeterInfoModel meterInfoModel = ctx.state.meterInfoModel;
      ResultData res = await CommonNetWork.addMeter(
        meterBiaoxiang: meterInfoModel.meterBiaoxiang,
        meterBaseVolume: meterInfoModel.meterBaseVolume,
        meterType: meterInfoModel.meterType,
        meterInstallType: meterInfoModel.meterInstallType.toString(),
        meterNo: meterInfoModel.meterNo,
        meterMemo: meterInfoModel.meterMemo,
        isClosed: meterInfoModel.isClosed,
        meterFengNumber: meterInfoModel.meterFengNumber,
        meterFactory: meterInfoModel.meterFactory,
        meterUnitType: meterInfoModel.meterUnitType,
        meterSpecs: meterInfoModel.meterSpecs,
        meterCtrlCode: meterInfoModel.meterCtrlCode,
        meterFeeMode: meterInfoModel.meterFeeMode,
        userIdNo: ctx.state.idCard,
        meterId: ctx.state.meterId,
      );
      Navigator.pop(ctx.context);
      if (!res.success) {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
        return;
      }
      ctx.state.meterId = CommonUtils.checkNullToString(res.data['MeterId']);
      Map info = meterInfoModel.toOrderMap();
      bizMeterContent = convert.jsonEncode(info);
    }

    List<String> contentPhoto = [];
    CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
    List items = ctx.state.items.map((e) => e.toJson()).toList();
    for (var item in items) {
      List imgList = item['ImageList'];
      if (imgList != null && imgList.isNotEmpty) {
        List<String> uploads = await CommonNetWork.multiUploadImgs(imgList,
            userNo: ctx.state.model.itemID);
        if (uploads == null) {
          Navigator.pop(ctx.context);
          CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
          return;
        }
        item['ImageList'] = uploads;
        contentPhoto.addAll(uploads);
      }
    }
    String json = convert.jsonEncode(items);
//    print(json);

    List img = [];
    if (ctx.state.orderPhoto.isNotEmpty) {
      img.addAll(ctx.state.orderPhoto);
    }
    img.add(ctx.state.orderSignPhoto);
    List<String> images = await CommonNetWork.multiUploadImgs(img,
        userNo: ctx.state.model.itemID);
    if (images == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    List<String> orderPhoto = images.sublist(0, images.length - 1);

    Navigator.pop(ctx.context);
    CommonUtils.showWaitLoading(ctx.context, descText: '正在提交中');
    List materList = [];
    for (var item in ctx.state.materList) {
      if (item.number != 0) {
        materList.add(item.toMap());
      }
    }
    Map extendInfo = {};
    if (ctx.state.meterInfoModel != null) {
      extendInfo['idcard'] = ctx.state.idCard;
    }
    if (ctx.state.businessLicenseImg.isNotEmpty) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          ctx.state.businessLicenseImg,
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['businessLicenseImg'] = images.join(',');
    }
    if (ctx.state.pipelineImg.isNotEmpty) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          ctx.state.pipelineImg,
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['pipelineImg'] = images.join(',');
    }
    if (ctx.state.gasMeterImg.isNotEmpty) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          ctx.state.gasMeterImg,
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['gasMeterImg'] = images.join(',');
    }

    if (ctx.state.videoUrl.isNotEmpty) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          ctx.state.videoUrl,
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['vedioUrl'] = images.join(',');
    }

    if (ctx.state.panoramagramImg.isNotEmpty) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          ctx.state.panoramagramImg,
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['panoramagramImg'] = images.join(',');
    }

    double total = 0.0;
    for (var item in ctx.state.materList) {
      total += (item.price * item.number);
    }
    extendInfo['totalAmount'] = total;
    extendInfo['idCard'] = ctx.state.idCard;
    if (ctx.state.idCardBackImg != null) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          [ctx.state.idCardBackImg],
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['idCardBackImg'] = images.first;
    }
    if (ctx.state.idCardFrontImg != null) {
      List<String> images = await CommonNetWork.multiUploadImgs(
          [ctx.state.idCardFrontImg],
          userNo: ctx.state.model.itemID);
      if (images == null) {
        Navigator.pop(ctx.context);
        CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
        return;
      }
      extendInfo['idCardFrontImg'] = images.first;
    }
    extendInfo['remark'] =
        CommonUtils.checkNullToString(ctx.state.model.businessExtend['remark']);
    extendInfo['imgInfo'] = CommonUtils.checkNullToString(
        ctx.state.model.businessExtend['imgInfo']);
    ResultData res = await CommonNetWork.fixOrderSubmit(
      orderPhoto: orderPhoto.join(','),
      jsonContent: json,
      signPhoto: images.last,
      isSolve: ctx.state.isSolve,
      itemID: ctx.state.model.itemID,
      bizMeterContent: bizMeterContent,
      isSave: isSave,
      materList: materList,
      type: ctx.state.model.itemType,
      extendInfo: extendInfo,
    );

    Navigator.pop(ctx.context);
    if (res.success) {
      bus.emit('refreshList');
      await CommonUtils.showAlertView(ctx.context, '提交成功');
      Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
  }
}

void _onTapSign(Action action, Context<EngineerGasResultViewState> ctx) async {
  if (ctx.state.isDetail) {
    List<GalleryExampleItem> items = [
      GalleryExampleItem(
        id: '0',
        resource: ctx.state.orderSignPhoto,
      )
    ];
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: 0,
      galleryItems: items,
    );
  } else {
    var res = await CommonUtils.showActionSheet(ctx.context, button: ['修改']);
    if (res == 0) {
      var file =
          await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
      if (file != null) {
        ctx.state.orderSignPhoto = file;
        ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
      }
    }
  }
}

void _onTapResultPic(
    Action action, Context<EngineerGasResultViewState> ctx) async {
  NormalConfigModel model = action.payload['model'];
  var file = action.payload['data'];
  await CommonUtils.showMediaAlbumView(
    ctx.context,
    initialIndex: model.imageList.indexOf(file),
    files: model.imageList,
  );
}

void _onTapAddGasPic(
    Action action, Context<EngineerGasResultViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 2, info: ctx.state.model);
  if (imgFile != null) {
    if (action.payload == 'gasMeterImg') {
      ctx.state.gasMeterImg.add(imgFile);
    }
    if (action.payload == 'pipelineImg') {
      ctx.state.pipelineImg.add(imgFile);
    }
    if (action.payload == 'businessLicenseImg') {
      ctx.state.businessLicenseImg.add(imgFile);
    }
    if (action.payload == 'panoramagramImg') {
      ctx.state.panoramagramImg.add(imgFile);
    }
    if (action.payload == 'videoUrl') {
      ctx.state.videoUrl.add(imgFile);
    }
    ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
  }
}

void _onTapGasPic(
    Action action, Context<EngineerGasResultViewState> ctx) async {
  List photos = [];

  if (action.payload['type'] == 'gasMeterImg') {
    photos = ctx.state.gasMeterImg;
  }
  if (action.payload['type'] == 'pipelineImg') {
    photos = ctx.state.pipelineImg;
  }
  if (action.payload['type'] == 'businessLicenseImg') {
    photos = ctx.state.businessLicenseImg;
  }
  if (action.payload['type'] == 'panoramagramImg') {
    photos = ctx.state.panoramagramImg;
  }
  if (action.payload['type'] == 'videoUrl') {
    photos = ctx.state.videoUrl;
  }
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: photos.indexOf(file),
      files: photos,
    );
  }

  var file = action.payload['data'];
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
        await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      photos.remove(file);
      ctx.dispatch(EngineerGasResultViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}
